package org.jeecg.modules.basic.demo.student.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.IdGeneratorSnowflake;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.bed.service.ILwgyBaseBedService;
import org.jeecg.modules.basic.demo.school.entity.LwgyBaseSchool;
import org.jeecg.modules.basic.demo.school.service.ILwgyBaseSchoolService;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.demo.student.mapper.LwgyBaseStudentMapper;
import org.jeecg.modules.basic.demo.student.service.ILwgyBaseStudentService;
import org.jeecg.modules.basic.demo.student.utils.PinYinUtil;
import org.jeecg.modules.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @Description: lwgy_base_student
 * @Author: jeecg-boot
 * @Date: 2020-12-11
 * @Version: V1.0
 */
@Service
public class LwgyBaseStudentServiceImpl extends ServiceImpl<LwgyBaseStudentMapper, LwgyBaseStudent> implements ILwgyBaseStudentService {

    @Autowired
    private ILwgyBaseBedService lwgyBaseBedService;

    @Resource
    private LwgyBaseStudentMapper lwgyBaseStudentMapper;

    @Autowired
    private ILwgyBaseSchoolService lwgyBaseSchoolService;


    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private IdGeneratorSnowflake snowflake;

    @Override
    public IPage<LwgyBaseStudent> queryStudentByCode(Page<LwgyBaseStudent> page, LwgyBaseSchool lwgyBaseSchool, String studentSex, String studentNumber) {
        QueryWrapper<LwgyBaseStudent> queryWrapper = new QueryWrapper<>();
        String universitySort = lwgyBaseSchool.getUniversitySort();
        String id = lwgyBaseSchool.getId();
        queryWrapper.eq("s.student_sex", studentSex);
        if (oConvertUtils.isNotEmpty(studentNumber)) {
            queryWrapper.likeRight("s.studentNumber", studentNumber);
        }
        switch (universitySort) {
            case "campus":
                queryWrapper.eq("s.student_campus", id);
                break;
            case "faculty":
                queryWrapper.eq("s.student_college", id);
                break;
            case "grade":
                queryWrapper.eq("s.student_year", id);
                break;
            case "major":
                queryWrapper.eq("s.student_major", id);
                break;
            case "class":
                queryWrapper.eq("s.student_class", id);
                break;
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> role = lwgyBaseBedService.getRoleById(sysUser.getId());
        if (!role.contains("admin")) {//不是管理员，显示辅导员所在班级的学生

            List<String> classId = getClassIdBySysUser(sysUser);
            if (oConvertUtils.listIsNotEmpty((classId))) {
                queryWrapper.in("s.student_class", classId);
            } else {
                queryWrapper.eq("s.student_class", "null");
            }
           /*   String selectedSchools = sysUser.getSelectedSchools();
                if(oConvertUtils.isNotEmpty(selectedSchools)){
                String[] fields = selectedSchools.trim().split(",");
                QueryWrapper<LwgyBaseSchool> queryWrapperScl = new QueryWrapper<>();
                queryWrapperScl.in("sys_org_code",Arrays.asList(fields));
                List<LwgyBaseSchool> schoolList = lwgyBaseSchoolService.getBaseMapper().selectList(queryWrapperScl);
                List<String> classId = getClassId(schoolList);
            }*/

        }
        return page.setRecords(lwgyBaseStudentMapper.queryStudentByCode(page, queryWrapper));
    }

    @Override
    public IPage<LwgyBaseStudent> queryPageListStudent(Page<LwgyBaseStudent> page, QueryWrapper<LwgyBaseStudent> queryWrapper) {
        return page.setRecords(lwgyBaseStudentMapper.queryPageListStudent(page, queryWrapper));
    }

    /**
     * 查找机构下的id
     *
     * @param schoolList
     * @return
     */
    private List<String> getClassId(List<LwgyBaseSchool> schoolList) {
        QueryWrapper<LwgyBaseSchool> queryWrapperScl = new QueryWrapper<>();
        queryWrapperScl.select("id", "university_sort");
        queryWrapperScl.eq("university_sort", "class");
        queryWrapperScl.and(wapper -> {
            for (LwgyBaseSchool baseSchool : schoolList) {
                wapper.or().likeRight("sys_org_code", baseSchool.getSysOrgCode());
            }
        });
        List<LwgyBaseSchool> classList = lwgyBaseSchoolService.getBaseMapper().selectList(queryWrapperScl);
        List<String> strings = new ArrayList<>(classList.size());
        classList.stream().forEach(item -> strings.add(item.getId()));
        List<String> classId = strings.stream().distinct().collect(Collectors.toList());//去重
        return classId;
    }

    @Override
    public IPage<LwgyBaseStudent> queryStuByNum(Page<LwgyBaseStudent> page, QueryWrapper<LwgyBaseStudent> queryWrapper) {
        page.setOptimizeCountSql(false);//解决聚合函数无法计算分页，更好的解决方案在这-->>> https://blog.csdn.net/qq_36457702/article/details/104445252
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> role = lwgyBaseBedService.getRoleById(sysUser.getId());
        if (!role.contains("admin")) {//不是管理员，显示辅导员所在班级的学生
            List<String> classId = getClassIdBySysUser(sysUser);
            if (oConvertUtils.listIsNotEmpty((classId))) {
                queryWrapper.in("s.student_class", classId);
            } else {
                queryWrapper.eq("s.student_class", "null");
            }
            /*String selectedSchools = sysUser.getSelectedSchools();
            if(oConvertUtils.isNotEmpty(selectedSchools)){
                String[] fields = selectedSchools.trim().split(",");
                QueryWrapper<LwgyBaseSchool> queryWrapperScl = new QueryWrapper<>();
                queryWrapperScl.in("sys_org_code",Arrays.asList(fields));
                List<LwgyBaseSchool> schoolList = lwgyBaseSchoolService.getBaseMapper().selectList(queryWrapperScl);
                List<String> classId = getClassId(schoolList);
            }*/
        }
        return page.setRecords(lwgyBaseStudentMapper.queryStuByNum(page, queryWrapper));
    }

    /**
     * 拒绝递归查询
     */
    List<String> strings = new CopyOnWriteArrayList<>();

    @Deprecated
    private void getSchoolClassId(List<LwgyBaseSchool> schoolList) {

        for (LwgyBaseSchool lwgyBaseSchool : schoolList) {
            if ("class".equals(lwgyBaseSchool.getUniversitySort())) {
                strings.add(lwgyBaseSchool.getId());
            } else {
                schoolList = lwgyBaseSchoolService.getTreeChild(lwgyBaseSchool.getId());
                getSchoolClassId(schoolList);
            }
        }
    }


    @Override
    public IPage<LwgyBaseStudent> queryPageCustomer(Page<LwgyBaseStudent> page, QueryWrapper<LwgyBaseStudent> queryWrapper) {
        queryWrapper.isNotNull("stu.id");
        return page.setRecords(lwgyBaseStudentMapper.queryPageListCustom(page, queryWrapper));
    }

    @Override
    public IPage<LwgyBaseStudent> queryPageLeaveStudent(Page<LwgyBaseStudent> page, QueryWrapper<LwgyBaseStudent> queryWrapper,String studentState) {

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        String leaveTime = "";
        if(month>9){
            //明年毕业生
            year = year+1;
            leaveTime = year+"-09-01 00:00:00";
        }else{
            //今年以及之前的毕业生
            year = year;
            leaveTime = year+"-09-01 00:00:00";
        }
        queryWrapper.isNotNull("ls.id");
        if(studentState.equals("0")){
            queryWrapper.lt("student_leaveschool",leaveTime);
        }

        return page.setRecords(lwgyBaseStudentMapper.queryLeaveStudent(page, queryWrapper,leaveTime));
    }

    @Override
    public List<Map<String, String>> listByPid(String pid) {
        List<Map<String, String>> list = lwgyBaseStudentMapper.listByPid(pid);

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> role = lwgyBaseBedService.getRoleById(sysUser.getId());
   /*     if (role.contains("fdy")) {//不是管理员，显示辅导员所在班级的学生
            List<Map<String, String>> list2 = new ArrayList<Map<String, String>>();
            String selectedSchools = sysUser.getSelectedSchools();
            if (oConvertUtils.isNotEmpty(selectedSchools)) {
                String[] fields = selectedSchools.trim().split(",");
                QueryWrapper<LwgyBaseSchool> queryWrapperScl = new QueryWrapper<>();
                queryWrapperScl.in("sys_org_code", Arrays.asList(fields));
                List<LwgyBaseSchool> schoolList = lwgyBaseSchoolService.getBaseMapper().selectList(queryWrapperScl);

                list.stream().forEach(item -> {
                    schoolList.stream().forEach(item2 -> {
                        if (String.valueOf(item.get("id")).equals(item2.getId())) {
                            list2.add(item);
                        }
                    });
                });
            }
            return list2;
        }*/

        return list;
    }
    @Override
    public List<Map<String, String>> listByName(String name) {
        List<Map<String, String>> list = lwgyBaseStudentMapper.listByName(name);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> role = lwgyBaseBedService.getRoleById(sysUser.getId());
        return list;
    }
    //平面图
    @Override
    public List<Map<String, String>> listByPid2(String pid) {
        List<Map<String, String>> list = lwgyBaseStudentMapper.listByPid(pid);

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> role = lwgyBaseBedService.getRoleById(sysUser.getId());
        if (role.contains("fdy")) {//不是管理员，显示辅导员所在班级的学生
            List<Map<String, String>> list2 = new ArrayList<Map<String, String>>();
            String selectedSchools = sysUser.getSelectedSchools();
            if (oConvertUtils.isNotEmpty(selectedSchools)) {
                String[] fields = selectedSchools.trim().split(",");
                QueryWrapper<LwgyBaseSchool> queryWrapperScl = new QueryWrapper<>();
                queryWrapperScl.in("sys_org_code", Arrays.asList(fields));
                List<LwgyBaseSchool> schoolList = lwgyBaseSchoolService.getBaseMapper().selectList(queryWrapperScl);

                list.stream().forEach(item -> {
                    schoolList.stream().forEach(item2 -> {
                        if (String.valueOf(item.get("id")).equals(item2.getId())) {
                            list2.add(item);
                        }
                    });
                });
            }
            return list2;
        }
//        if (role.contains("yanjiusheng")) {
//
//            System.err.println("走这里了！！！");
//            List<Map<String, String>> list2 = new ArrayList<Map<String, String>>();
//            String education = sysUser.getSelectedEducation();
//            if (oConvertUtils.isNotEmpty( education)) {
//                System.err.println("classId:::" +  education);
//                String[] fieldss = education.split(",");
//                QueryWrapper<LwgyBaseStudent> queryWrapperScl = new QueryWrapper<>();
//                queryWrapperScl.in("student_education", Arrays.asList(fieldss));
//                List<LwgyBaseStudent> schoolList = this.getBaseMapper().selectList(queryWrapperScl);
//
//                list.stream().forEach(item -> {
//                    schoolList.stream().forEach(item2 -> {
//                        if (String.valueOf(item.get("id")).equals(item2.getId())) {
//                            list2.add(item);
//                        }
//                    });
//                });
//            }
//            return list2;
//        }



        return list;
    }

    @Override
    public String getStuIdByNumber(String studentNumber) {
        QueryWrapper<LwgyBaseStudent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_number", studentNumber);
        queryWrapper.select("id");
        return lwgyBaseStudentMapper.selectOne(queryWrapper).getId();
    }

    @Override
    public List<Map<String, String>> getStuInfoById(String id) {
        return lwgyBaseStudentMapper.getStuInfoById(id);
    }

    @Override
    public List<String> getClassIdBySysUser(LoginUser sysUser) {
        String selectedSchools = sysUser.getSelectedSchools();
        if (oConvertUtils.isNotEmpty(selectedSchools)) {
            String[] fields = selectedSchools.split(",");
            QueryWrapper<LwgyBaseSchool> queryWrapperScl = new QueryWrapper<>();
            queryWrapperScl.in("sys_org_code", Arrays.asList(fields));
            List<LwgyBaseSchool> schoolList = lwgyBaseSchoolService.getBaseMapper().selectList(queryWrapperScl);
            List<LwgyBaseSchool> endSchoolList = new ArrayList<LwgyBaseSchool>();
            //取所有学校级别的数据及下属班级
            List<LwgyBaseSchool> list1 = schoolList.stream().filter(item->item.getUniversitySort().equals("campus")).collect(Collectors.toList());
            //取所有学院级别的数据及下属班级
            List<LwgyBaseSchool> list2 = schoolList.stream().filter(item->item.getUniversitySort().equals("faculty")).collect(Collectors.toList());
            //取所有年级级别的数据及下属班级
            List<LwgyBaseSchool> list3 = schoolList.stream().filter(item->item.getUniversitySort().equals("grade")).collect(Collectors.toList());
            //取所有专业级别的数据及下属班级
            List<LwgyBaseSchool> list4 = schoolList.stream().filter(item->item.getUniversitySort().equals("major")).collect(Collectors.toList());
            //取所有班级级别的数据及下属班级
            List<LwgyBaseSchool> list5 = schoolList.stream().filter(item->item.getUniversitySort().equals("class")).collect(Collectors.toList());

            //辅导员权限绑定到班级，数据以班级为准，否则逐级上找，如果只绑定学院（list1）就获取该学院下所有班级
            if(oConvertUtils.listIsNotEmpty(list5)){
                //绑定班级，以班级为准
                return getClassId(list5);
            }else  if(oConvertUtils.listIsNotEmpty(list4)){

                //班级为空，绑定专业，以专业为准
                return getClassId(list4);
            }else if(oConvertUtils.listIsNotEmpty(list3)){
                //班级专业为空，绑定年级，以年级为准
                return getClassId(list3);
            }else if(oConvertUtils.listIsNotEmpty(list2)){
                //班级专业年级为空，绑定学院，以学院为准
                return getClassId(list2);
            }else if(oConvertUtils.listIsNotEmpty(list1)){
                //班级专业年纪学院为空，绑定校区，以校区为准
                return getClassId(list1);
            }
        }
        return new ArrayList<>();
    }

    @Override
    public List<LwgyBaseStudent> getNotAccountStuList() {
        return lwgyBaseStudentMapper.getNotAccountStuList();
    }

    @Override
    public List<LwgyBaseStudent> getStudentInfo() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> role = lwgyBaseBedService.getRoleById(sysUser.getId());
        QueryWrapper<LwgyBaseStudent> queryWrapper = new QueryWrapper<>();
        if (!role.contains("admin")) {//不是管理员，显示辅导员所在班级的学生
            List<String> classId = getClassIdBySysUser(sysUser);
            if (oConvertUtils.listIsNotEmpty((classId))) {
                queryWrapper.in("s.student_class", classId);
            } else {
                queryWrapper.eq("s.student_class", "null");
            }
        }
        return lwgyBaseStudentMapper.queryStuByNum(null, queryWrapper);
    }

    @Override
    public List<LwgyBaseStudent> exportXlsStu(LwgyBaseStudent lwgyStudent) {
        return null;
    }

    @Override
    public List<String> getAllSysUser() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roles = sysBaseAPI.getRolesByUsername(sysUser.getUsername());
        QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("username");
        if (!roles.contains("admin")) {
            String selectedSchools = sysUser.getSelectedSchools();
            if (oConvertUtils.isNotEmpty(selectedSchools)) {
                String[] fields = selectedSchools.split(",");
                queryWrapper.and(wapper -> {
                    for (String field : fields) {
                        wapper.or().likeRight("selected_schools", field);
                    }
                });
            } else {//没有绑定的学院
                queryWrapper.eq("selected_schools", "null");
            }
        }
        return lwgyBaseStudentMapper.getAllSysUser(queryWrapper);
    }
/*
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer generateStuAccount() {
        List<LwgyBaseStudent> lwgyBaseStudents = getStudentInfo();//获取自己的学生
        List<LwgyBaseSchool> lwgyBaseSchools = lwgyBaseSchoolService.getSysOrgCode();//key:id,value:sysOrg
        Map<String, String> idAndSysOrgCode = lwgyBaseSchools.stream().collect(Collectors.toMap(LwgyBaseSchool::getId, LwgyBaseSchool::getSysOrgCode));

        List<String> sysUsernameList = getAllSysUser();//获取全部用户
        List<String> allUsername = new ArrayList<>(lwgyBaseStudents.size() + sysUsernameList.size());
        lwgyBaseStudents.stream().forEach(lwgyBaseStudent -> allUsername.add(lwgyBaseStudent.getStudentNumber()));
        allUsername.addAll(sysUsernameList);//相加取并集
        List<String> distinctList = allUsername.stream().distinct().collect(Collectors.toList());//去重
        List<String> collect = distinctList.stream().filter(item -> !sysUsernameList.contains(item)).collect(Collectors.toList());
        List<LwgyBaseStudent> lwgyBaseStudentList = lwgyBaseStudents.stream().filter(stu -> collect.contains(stu.getStudentNumber())).collect(Collectors.toList());

        String roleId = sysBaseAPI.getRolesIdByName("学生");//获取学生的角色id
        List<SysUser> sysUsers = new ArrayList<>(lwgyBaseStudentList.size());
        lwgyBaseStudentList.stream().forEach(stuInfo -> {//遍历没有账号的所有学生的信息
            SysUser sysUser = new SysUser();
            sysUser.setId(String.valueOf(snowflake.snowflakeId()));//直接设置上id，供后期批量创建角色信息时使用
            String studentNumber = stuInfo.getStudentNumber();
            sysUser.setUsername(studentNumber);//使用学号作为登录名
            sysUser.setWorkNo(studentNumber);//工号
            String salt = oConvertUtils.randomGen(8);//获取加密salt
            sysUser.setSalt(salt);
            sysUser.setDelFlag(0);//未删除
            sysUser.setSex(Integer.parseInt(stuInfo.getStudentSex()));//性别
            sysUser.setRealname(stuInfo.getStudentName());//真实姓名
            StringBuilder password = new StringBuilder("@");
            //获取名字全拼，去掉中间的空格和字符
            String pinyin = PinYinUtil.getPinyin(stuInfo.getStudentName()).replaceAll("\\s*", "").replaceAll("[^(A-Za-z)]", "").toLowerCase();//获取名字全拼
            //so passwd rule is: @ + 名字全拼 + 学号后两位
            password.append(pinyin).append(studentNumber.substring(studentNumber.length() - 2));
            String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), password.toString(), salt);
            sysUser.setUserIdentity(1);//普通用户
            sysUser.setStatus(1);//正常
            sysUser.setPassword(passwordEncode);//密码
            sysUser.setSelectedSchools(idAndSysOrgCode.get(stuInfo.getStudentClass()));
            sysUsers.add(sysUser);
        });
        sysBaseAPI.batchSaveSysUser(sysUsers, roleId);//生成角色权限对应数据
        return sysUsers.size();
    }*/

    @Override
    public List<LwgyBaseStudent> getStuListByStuNumber(String[] studentId){
        return lwgyBaseStudentMapper.getStuListByStuNumber(studentId);
    }

    @Override
    public List<LwgyBaseStudent> getListByJob(QueryWrapper<LwgyBaseStudent> queryWrapper) {
        return lwgyBaseStudentMapper.getListByJob(queryWrapper);
    }

}
